<template>
  <list-condition-template ref="table" :rows="rows" :total="total" @page-info-change="handlePageInfoChange" :defaultSort="{ prop: 'createTime', order: 'descending' }">
    <template slot="condition">
      <el-form-item>
        <el-input @keyup.enter.native="handleFilter" placeholder="名称或账号" v-model.trim="listQuery.condition.keyword" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-select @change="handleFilter" clearable style="width: 150px" class="filter-item" placeholder="状态" v-model="listQuery.condition.status">
          <el-option v-for="item in stateOptions" :key="item.name" :label="item.name" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      </el-form-item> -->
    </template>
     <template slot="normalOperation">
      <el-form-item>
        <el-button class="filter-item" @click="handleCreate" type="primary" icon="el-icon-plus" v-waves>新增</el-button>
      </el-form-item>
    </template>
    <template slot="columns">
      <el-table-column min-width="150px" label="账号" sortable="custom" property="account" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.account.account}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="150px" label="名称" align="center" sortable="custom" property="nickname">
        <template slot-scope="scope">
          <span>{{scope.row.nickname}}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" align="center" label="状态" width="150px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.account.status | showFilter">{{scope.row.account.status===1 ? '启用' : '禁用'}}</el-tag>
        </template>
      </el-table-column>
        <el-table-column label="创建时间" min-width="100" align="center" sortable="custom" property="createTime"></el-table-column>
      <el-table-column label="更新时间" min-width="100" align="center" sortable="custom" property="updateTime"></el-table-column>
      <el-table-column align="center" label="操作" width="240px" class-name="fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)" v-waves>修改</el-button>
          <el-button size="mini" :type="scope.row.account.status | showButtonFilter" @click="handleState(scope.row)" v-waves>{{scope.row.account.status===1 ? '禁用' : '启用'}}</el-button>
          <el-button size="mini" type="info" @click="handleChangeUserPassword(scope.row)" v-waves>重置密码</el-button>
        </template>
      </el-table-column>
    </template>

    <el-dialog :title="changePassword.title" :visible.sync="changePassword.show" width="40%" @close="handleChangePasswordDialogClose">
      <el-form size="mini" ref="changePasswordForm" :model="changePassword.formData" :rules="changePassword.rules" label-width="120px" status-icon>
        <el-form-item label="密码" prop="password">
          <el-input type="password" placeholder="请输入密码" v-model="changePassword.formData.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input type="password" placeholder="请再次输入密码" v-model="changePassword.formData.checkPassword" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="changePassword.show = false">取消</el-button>
        <el-button size="mini" type="primary" @click="handleDoChangeUserPassword" :loading="changePassword.loading">{{changePassword.loading ? '提交中' : '确定'}}</el-button>
      </span>
    </el-dialog>
  </list-condition-template>
</template>

<script>
import adminUserApi from '@/api/admin/adminUser'
import waves from '@/directive/waves' // 水波纹指令
import ListConditionTemplate from '@/components/templates/listConditionTemplate'

export default {
  directives: {
    waves
  },
  components: {
    ListConditionTemplate
  },
  data () {
    return {
      rows: null,
      total: 0,
      listQuery: {
        condition: {
          keyword: null,
          status: null
        },
        pageInfo: null
      },
      stateOptions: [
        {
          name: '启用',
          value: 1
        },
        {
          name: '禁用',
          value: 0
        }
      ],
      changePassword: {
        formData: {
          password: '',
          checkPassword: '',
          accountId: '',
          userId: undefined
        },
        title: '修改密码',
        show: false,
        loading: false,
        rules: {
          password: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (value === '') {
                  callback(new Error('请输入密码'))
                } else if (value.length < 6 || value.length > 20) {
                  callback(new Error('密码长度需在6到20之间'))
                } else {
                  if (this.changePassword.formData.checkPassword !== '') {
                    this.$refs.changePasswordForm.validateField(
                      'checkPassword'
                    )
                  }
                  callback()
                }
              },
              trigger: 'blur'
            }
          ],
          checkPassword: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (value === '') {
                  callback(new Error('请再次输入密码'))
                } else if (value.length < 6 || value.length > 20) {
                  callback(new Error('密码长度需在6到20之间'))
                } else if (value !== this.changePassword.formData.password) {
                  callback(new Error('两次输入密码不一致'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ]
        }
      }
    }
  },
  filters: {
    /**
     * 表格行显示状态过滤
     * @param {*} show 显示状态
     */
    showFilter (show) {
      return show === 1 ? 'success' : 'danger'
    },
    /**
     * 表格按钮显示状态过滤
     * @param {*} show 显示状态
     */
    showButtonFilter (show) {
      return show !== 1 ? 'success' : 'danger'
    }
  },
  methods: {
    /**
     * 加载数据
     */
    getList (pageInfo) {
      this.listQuery.pageInfo = pageInfo
      adminUserApi
        .getPaged(this.listQuery)
        .then(response => {
          this.rows = response.data.content
          this.total = response.data.totalElements
        })
    },
    /**
     * 搜索条件变更处理
     */
    handleFilter () {
      this.$refs.table.changeCondition()
    },
    /**
     * 分页信息变动事件处理
     * @param  {Object} pageInfo 分页信息
     */
    handlePageInfoChange (pageInfo) {
      this.getList(pageInfo)
    },
    /**
     * 新增按钮点击处理
     */
    handleCreate () {
      this.$router.pushTo(this.$router.routesConfig.adminNew)
    },
    /**
     * 修改按钮点击处理
     * @param {*} row 参数
     */
    handleUpdate (row) {
      this.$router.pushTo(this.$router.routesConfig.adminEdit, row.id)
    },
    /**
     * 启用、停用按钮点击处理
     * @param {*} row 参数
     */
    handleState (row) {
      const enabled = row.account.status === 1
      adminUserApi
        .setState({ accountId: row.account.id, enabled: !enabled })
        .then(response => {
          row.account.status = response.data.status
        })
    },
    /**
     * 重置密码按钮点击处理
     * @param {*} row 参数
     */
    handleChangeUserPassword (row) {
      this.changePassword.show = true
      this.changePassword.title = `重置密码 - ${row.nickname}`
      this.changePassword.formData.userId = row.id
      this.changePassword.formData.accountId = row.account.id
    },
    /**
     * 重置密码
     */
    handleDoChangeUserPassword () {
      this.$refs.changePasswordForm.validate().then(pass => {
        if (pass) {
          this.changePassword.loading = true
          adminUserApi
            .resetPassword({
              id: this.changePassword.formData.accountId,
              newPassword: this.changePassword.formData.password
            })
            .then(response => {
              this.changePassword.loading = false
              this.changePassword.show = false
              this.changePassword.formData.userId = undefined
              this.$notify({
                title: '成功',
                message: '密码重置成功',
                type: 'success'
              })
            })
            .catch(response => {
              this.changePassword.loading = false
            })
        }
      })
    },
    /**
     * 重置密码对话框关闭事件处理
     */
    handleChangePasswordDialogClose () {
      this.$refs.changePasswordForm.resetFields()
    }
  }
}
</script>
